// - game.js ：原生JS实现，直接操作DOM
// - SnakeGame.vue ：Vue 3响应式实现，使用Composition API
// 两个文件的关系类似于同一功能的两种不同技术实现方案，但Vue项目中应该只保留 SnakeGame.vue 组件作为主实现
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 20;
const tileCount = canvas.width / gridSize;

let snake = [
  {x: 10, y: 10}
];
let food = {x: 15, y: 15};
let dx = 0;
let dy = 0;
let score = 0;
let gameSpeed = 100;
let gameLoop;

function drawGame() {
  // 移动蛇
  const head = {x: snake[0].x + dx, y: snake[0].y + dy};
  snake.unshift(head);

  // 检测食物碰撞
  if (head.x === food.x && head.y === food.y) {
    score += 10;
    document.getElementById('score').textContent = score;
    generateFood();
    if (score % 50 === 0) {
      gameSpeed *= 0.8;
      clearInterval(gameLoop);
      gameLoop = setInterval(drawGame, gameSpeed);
    }
  } else {
    snake.pop();
  }

  // 碰撞检测
  if (isCollision()) {
    gameOver();
    return;
  }

  // 清空画布
  ctx.fillStyle = 'white';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 绘制蛇
  ctx.fillStyle = '#4CAF50';
  snake.forEach((segment, index) => {
    ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize-2, gridSize-2);
  });

  // 绘制食物
  ctx.fillStyle = 'red';
  ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize-2, gridSize-2);
}

function generateFood() {
  food.x = Math.floor(Math.random() * tileCount);
  food.y = Math.floor(Math.random() * tileCount);
  // 确保食物不在蛇身上
  if (snake.some(segment => segment.x === food.x && segment.y === food.y)) {
    generateFood();
  }
}

function isCollision() {
  const head = snake[0];
  return (
    head.x < 0 || 
    head.x >= tileCount || 
    head.y < 0 || 
    head.y >= tileCount ||
    snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y)
  );
}

function gameOver() {
  clearInterval(gameLoop);
  alert('游戏结束！得分：' + score);
  document.addEventListener('keydown', startGame);
}

function startGame(event) {
  if (event.code === 'Space') {
    snake = [{x: 10, y: 10}];
    dx = 0;
    dy = 0;
    score = 0;
    gameSpeed = 100;
    document.getElementById('score').textContent = '0';
    document.removeEventListener('keydown', startGame);
    gameLoop = setInterval(drawGame, gameSpeed);
  }
}

// 键盘控制
document.addEventListener('keydown', (event) => {
  switch(event.key) {
    case 'ArrowUp':
      if (dy !== 1) { dx = 0; dy = -1; }
      break;
    case 'ArrowDown':
      if (dy !== -1) { dx = 0; dy = 1; }
      break;
    case 'ArrowLeft':
      if (dx !== 1) { dx = -1; dy = 0; }
      break;
    case 'ArrowRight':
      if (dx !== -1) { dx = 1; dy = 0; }
      break;
  }
});

document.addEventListener('keydown', startGame);
alert('按空格键开始游戏！');